package com.sff.easyexcel.test.demo.template;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable;
import com.sff.easyexcel.test.demo.util.FilePathUtil;

import java.util.List;

/**
 * 手动创建不规则表头导出
 * 1.合并单元格创建不规则表头
 */
public class CreateHeadByMergeCell {

    public static void main(String[] args) {

        String writeFileName = FilePathUtil.getPath() + "create-head" + System.currentTimeMillis() + ".xlsx";
        ExcelWriter writer = EasyExcel.write(writeFileName).build();

        // 动态添加表头，适用一些表头动态变化的场景
        WriteSheet sheet1 = new WriteSheet();
        sheet1.setSheetName("商品明细");
        sheet1.setSheetNo(0);

        // 创建一个表格，用于 Sheet 中使用
        WriteTable table = new WriteTable();
        table.setTableNo(1);
        table.setHead(createHead());

        // 写数据
        writer.write(contentData(), sheet1, table);
        writer.finish();

    }

    private static List<List<String>> createHead() {
        List<List<String>> headTitles = ListUtils.newArrayList();
        String basicInfo = "基础资料", skuInfo = "商品扩展", orderInfo = "经营情况", empty = " ";
        //第一列，1/2/3行
        headTitles.add(ListUtils.newArrayList(basicInfo, basicInfo, "类别"));
        //第二列，1/2/3行
        headTitles.add(ListUtils.newArrayList(basicInfo, basicInfo, "名称"));

        List<String> skuTitles = ListUtils.newArrayList("组合商品", "上一次优惠时间", "销售次数", "库存", "价格");
        skuTitles.forEach(title -> {
            headTitles.add(ListUtils.newArrayList(skuInfo, skuInfo, title));
        });

        //动态根据月份生成
        List<Integer> monthList = ListUtils.newArrayList(5, 6);
        List<String> orderSpeaces = ListUtils.newArrayList("销售额", "客流", "利润");
        monthList.forEach(month -> {
            orderSpeaces.forEach(title -> {
                headTitles.add(ListUtils.newArrayList(orderInfo, month + "月", title));
            });
        });

        //无一、二行标题
        List<String> lastList = ListUtils.newArrayList("日均销售金额(元)", "月均销售金额(元)");
        lastList.forEach(title -> {
            headTitles.add(ListUtils.newArrayList(empty, empty, title));
        });

        return headTitles;
    }

    private static List<List<Object>> contentData() {

        List<List<Object>> contentList = ListUtils.newArrayList();
        //这里一个List<Object>才代表一行数据，需要映射成每行数据填充，横向填充（把实体数据的字段设置成一个List<Object>）
        contentList.add(ListUtils.newArrayList("测试", "商品A", "苹果"));
        contentList.add(ListUtils.newArrayList("测试", "商品B", "橙子"));
        return contentList;
    }

}
